package com.lily.ssm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lily.ssm.model.Message;
import com.lily.ssm.model.Pager;
import com.lily.ssm.model.Product;
import com.lily.ssm.model.ProductClass;
import com.lily.ssm.service.MessageService;

@Controller
public class MessageController {
	
	@Autowired
	private MessageService messageService;
	
	/*
	 * 查询所有留言并在页面显示
	 */
	@RequestMapping("/selectMessage.do")
	public String selectMessage(Pager<Message> pager,Model model){
		//更改每页默认显示的页数
		pager.setPageSize(5);
		// 分页查询数据
		List<Message> messages = messageService.getMessageList(pager.getOffset());
		
		// 查询共有Product多少条数据，存入Pager中
		pager.setCount(messageService.getCount());
		// 判断接受的pageIndex是否为0，为0的话赋予默认值1
		int index = pager.getPageIndex();
		index = index == 0 ? 1 : index;
		// 将返回的pagerIndex存入pager中
		pager.setPageIndex(index);
		// 将分页查询的数据存入pager中
		pager.setDatas(messages);
		
		// 将pager传到页面
		model.addAttribute("pager", pager);
		return "manage/guestbook";
	}
	
	/*
	 * 回复留言
	 */
	@RequestMapping(value="/replyMessage.do",method=RequestMethod.GET)
	public String replyMessage(int messageId,Model model){
		Message message = messageService.getMessage(messageId);
		model.addAttribute("message", message);
		return "manage/guestbook-modify";
	}
	
	@RequestMapping(value="/replyMessage.do",method=RequestMethod.POST)
	public String replyMessage(int messageId,String responseContent){
		Message message = messageService.getMessage(messageId);
		message.setResponseContent(responseContent);
		if(responseContent != null && !"".equals(responseContent)){
			message.setMessageStatus(1);
		}else{
			message.setMessageStatus(0);
		}
		messageService.updateMessage(message);
		return "redirect:/selectMessage.do";
	}
	
	@RequestMapping("/deleteMessage.do")
	public String  deleteMessage(int messageId){
		messageService.deleteMessage(messageId);
		return "redirect:/selectMessage.do";
	}
}
